package com.example.cdctravel

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

@SuppressLint("ValidFragment")
class TabFragment_Find : Fragment() {
    protected var mView: View? = null
    var adapter: MyAdapter? = null
    private var mlist: RecyclerView? = null //转换为成员变量
    protected var mContext: Context? = null
    private var database: PlaceDatabase? = null
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        database = PlaceDatabase(context, PlaceDatabase.TABLE_NAME, null, 1)
        mlist = requireActivity().findViewById(R.id.recycler_view)
        showStagger()
        adapter!!.setOnItemClickListener(object : MyAdapter.OnItemClickListener {
            override fun onItemClick(view: View?, position: Int) {
                val data = adapter!!.getmData()!![position]
                val intent = Intent()
                intent.putExtra("id", data.id)
                intent.setClass(requireActivity(), Content::class.java)
                startActivity(intent)
            }
        })
        val sv = mView!!.findViewById<SearchView>(R.id.sv)
        sv.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean {
                key = newText
                refreshData()
                return false
            }
        })
    }

    private fun showStagger() {
        val layoutManager = StaggeredGridLayoutManager(2, LinearLayout.VERTICAL)
        //这只布局管理器方向
        layoutManager.reverseLayout = false
        mlist!!.layoutManager = layoutManager
        adapter = MyAdapter(requireContext())
        mlist!!.adapter = adapter
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mContext = activity
        mView = inflater.inflate(R.layout.find, container, false)
        return mView
    }

    private var key = ""
    override fun onResume() {
        super.onResume()
        refreshData()
    }

    private fun refreshData() {
        val list = database!!.find(key)
        adapter!!.setNewData(list)
    }

    companion object {
        private const val TAG = "TabFirstFragment"
    }
}
